<template>
  <div class="churn-prediction-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>用户流失预测</h2>
        <p>基于机器学习算法预测用户流失风险，提供精准的挽回策略建议</p>
      </div>
      <div class="header-actions">
        <el-button :icon="Refresh" @click="() => refreshData(true)">刷新数据</el-button>
        <el-button type="primary" :icon="MagicStick" @click="runPrediction" :loading="predicting">
          执行预测
        </el-button>
        <el-button :icon="Download" @click="exportResults">导出结果</el-button>
      </div>
    </div>

    <!-- 概览统计 -->
    <div class="overview-section">
      <el-row :gutter="24">
        <el-col :xs="12" :sm="6">
          <div class="metric-card high-risk">
            <div class="metric-icon">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="metric-content">
              <h3>{{ overviewData.highRiskCount }}</h3>
              <p>高风险用户</p>
              <span class="metric-change danger">+{{ overviewData.highRiskChange }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="metric-card medium-risk">
            <div class="metric-icon">
              <el-icon><InfoFilled /></el-icon>
            </div>
            <div class="metric-content">
              <h3>{{ overviewData.mediumRiskCount }}</h3>
              <p>中风险用户</p>
              <span class="metric-change warning">+{{ overviewData.mediumRiskChange }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="metric-card low-risk">
            <div class="metric-icon">
              <el-icon><SuccessFilled /></el-icon>
            </div>
            <div class="metric-content">
              <h3>{{ overviewData.lowRiskCount }}</h3>
              <p>低风险用户</p>
              <span class="metric-change success">-{{ overviewData.lowRiskChange }}%</span>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="metric-card model-accuracy">
            <div class="metric-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="metric-content">
              <h3>{{ overviewData.modelAccuracy }}%</h3>
              <p>模型准确率</p>
              <span class="metric-change success">+{{ overviewData.accuracyChange }}%</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="24">
      <!-- 左侧：流失风险分布和趋势 -->
      <el-col :xs="24" :lg="16">
        <!-- 流失风险分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>流失风险分布</h3>
              <div class="header-actions">
                <el-select v-model="riskTimeRange" size="small" style="width: 120px">
                  <el-option label="近7天" value="7d" />
                  <el-option label="近30天" value="30d" />
                  <el-option label="近90天" value="90d" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <PieChartComponent
              :data="riskDistributionData"
              :options="riskChartOptions"
              height="300px"
            />
          </div>
        </el-card>

        <!-- 流失趋势分析 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>流失趋势分析</h3>
              <div class="header-actions">
                <el-radio-group v-model="trendType" size="small">
                  <el-radio-button label="daily">日趋势</el-radio-button>
                  <el-radio-button label="weekly">周趋势</el-radio-button>
                  <el-radio-button label="monthly">月趋势</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <LineChart
              :data="trendChartData"
              :x-axis-data="trendLabels"
              height="360px"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：模型性能和特征重要性 -->
      <el-col :xs="24" :lg="8" class="right-column">
        <!-- 模型性能监控 -->
        <el-card class="performance-card">
          <template #header>
            <h3>模型性能监控</h3>
          </template>
          <div class="performance-metrics">
            <div class="metric-item">
              <span class="metric-label">准确率 (Accuracy)</span>
              <div class="metric-value">
                <el-progress :percentage="modelPerformance.accuracy" :stroke-width="8" />
                <span class="percentage">{{ modelPerformance.accuracy }}%</span>
              </div>
            </div>
            <div class="metric-item">
              <span class="metric-label">精确率 (Precision)</span>
              <div class="metric-value">
                <el-progress :percentage="modelPerformance.precision" :stroke-width="8" />
                <span class="percentage">{{ modelPerformance.precision }}%</span>
              </div>
            </div>
            <div class="metric-item">
              <span class="metric-label">召回率 (Recall)</span>
              <div class="metric-value">
                <el-progress :percentage="modelPerformance.recall" :stroke-width="8" />
                <span class="percentage">{{ modelPerformance.recall }}%</span>
              </div>
            </div>
            <div class="metric-item">
              <span class="metric-label">F1分数 (F1-Score)</span>
              <div class="metric-value">
                <el-progress :percentage="modelPerformance.f1Score" :stroke-width="8" />
                <span class="percentage">{{ modelPerformance.f1Score }}%</span>
              </div>
            </div>
          </div>
          <div class="model-info">
            <p><strong>模型版本:</strong> {{ modelPerformance.version }}</p>
            <p><strong>训练时间:</strong> {{ modelPerformance.trainTime }}</p>
            <p><strong>样本数量:</strong> {{ modelPerformance.sampleCount }}</p>
          </div>
        </el-card>

        <!-- 特征重要性 -->
        <el-card class="feature-importance-card">
          <template #header>
            <h3>特征重要性</h3>
          </template>
          <div class="feature-list">
            <div 
              v-for="feature in featureImportance" 
              :key="feature.name"
              class="feature-item"
            >
              <div class="feature-info">
                <span class="feature-name">{{ feature.name }}</span>
                <span class="feature-value">{{ feature.importance }}%</span>
              </div>
              <el-progress 
                :percentage="feature.importance" 
                :stroke-width="6"
                :show-text="false"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 高风险用户列表 -->
    <el-card class="risk-users-card">
      <template #header>
        <div class="card-header">
          <h3>高风险用户列表</h3>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户ID或姓名"
              :prefix-icon="Search"
              style="width: 200px; margin-right: 12px;"
              clearable
            />
            <el-select v-model="riskLevelFilter" placeholder="风险等级" style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="高风险" value="High" />
              <el-option label="中风险" value="Medium" />
              <el-option label="低风险" value="Low" />
            </el-select>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredRiskUsers" 
        v-loading="loading"
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column prop="userId" label="用户ID" min-width="100" />
        <el-table-column prop="userName" label="用户姓名" min-width="120" />
        <el-table-column prop="churnProbability" label="流失概率" min-width="150" sortable>
          <template #default="{ row }">
            <el-progress
              :percentage="Math.round(row.churnProbability * 100)"
              :stroke-width="8"
              :color="getRiskColor(row.riskLevel)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="riskLevel" label="风险等级" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getRiskTagType(row.riskLevel)">
              {{ getRiskLevelText(row.riskLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastActiveDate" label="最后活跃" min-width="120" />
        <el-table-column prop="totalOrders" label="历史订单" min-width="100" />
        <el-table-column prop="totalSpent" label="消费金额" min-width="120">
          <template #default="{ row }">
            ¥{{ row.totalSpent.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="avgOrderValue" label="平均订单" min-width="120">
          <template #default="{ row }">
            ¥{{ row.avgOrderValue.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewUserDetail(row)">详情</el-button>
            <el-button size="small" type="primary" @click="createRetentionStrategy(row)">
              制定策略
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalUsers"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情弹窗 -->
    <el-dialog
      v-model="userDetailVisible"
      title="用户详细信息"
      width="800px"
      :before-close="handleCloseUserDetail"
    >
      <UserDetailPanel 
        v-if="selectedUser"
        :user="selectedUser"
        :prediction-data="selectedUserPrediction"
      />
    </el-dialog>

    <!-- 挽回策略弹窗 -->
    <el-dialog
      v-model="strategyVisible"
      title="制定挽回策略"
      width="600px"
      :before-close="handleCloseStrategy"
    >
      <RetentionStrategyPanel 
        v-if="selectedUser"
        :user="selectedUser"
        @strategy-created="handleStrategyCreated"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh, MagicStick, Download, Warning, InfoFilled, SuccessFilled,
  TrendCharts, Search
} from '@element-plus/icons-vue'
import { LineChart, PieChart as PieChartComponent } from '@/components/charts'

// 导入API
import {
  getChurnOverview,
  getChurnRiskDistribution,
  getChurnTrendData,
  getChurnRiskUsers,
  runChurnPrediction,
  trainChurnModel
} from '@/api/prediction'

// 导入子组件
import UserDetailPanel from '@/components/prediction/UserDetailPanel.vue'
import RetentionStrategyPanel from '@/components/prediction/RetentionStrategyPanel.vue'

// 响应式数据
const loading = ref(false)
const predicting = ref(false)
const userDetailVisible = ref(false)
const strategyVisible = ref(false)
const selectedUser = ref(null)
const selectedUserPrediction = ref(null)

// 筛选和搜索
const searchKeyword = ref('')
const riskLevelFilter = ref('')
const riskTimeRange = ref('30d')
const trendType = ref('daily')

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalUsers = ref(0)

// 概览数据
const overviewData = reactive({
  highRiskCount: 1247,
  highRiskChange: 12.5,
  mediumRiskCount: 3891,
  mediumRiskChange: 8.3,
  lowRiskCount: 15623,
  lowRiskChange: 3.2,
  modelAccuracy: 87.5,
  accuracyChange: 2.1
})

// 模型性能数据
const modelPerformance = reactive({
  accuracy: 87.5,
  precision: 84.2,
  recall: 89.1,
  f1Score: 86.6,
  version: 'v2.1.0',
  trainTime: '2024-01-15 14:30:00',
  sampleCount: 50000
})

// 特征重要性数据
const featureImportance = ref([
  { name: '最后登录间隔', importance: 85 },
  { name: '购买频率', importance: 78 },
  { name: '平均订单金额', importance: 72 },
  { name: '客服咨询次数', importance: 65 },
  { name: '页面停留时间', importance: 58 },
  { name: '购物车放弃率', importance: 52 },
  { name: '优惠券使用率', importance: 45 },
  { name: '评价参与度', importance: 38 }
])

// 风险分布数据
const riskDistributionData = ref([
  { name: '高风险', value: 1247, color: '#F56C6C' },
  { name: '中风险', value: 3891, color: '#E6A23C' },
  { name: '低风险', value: 15623, color: '#67C23A' }
])

// 风险分布图表配置
const riskChartOptions = ref({
  title: '流失风险分布',
  showLegend: true,
  radius: ['40%', '70%']
})

// 趋势数据
const trendLabels = ref(['1月1日', '1月2日', '1月3日', '1月4日', '1月5日', '1月6日', '1月7日'])

const trendChartData = ref([
  {
    name: '高风险用户',
    data: [120, 135, 142, 158, 167, 175, 182]
  },
  {
    name: '中风险用户',
    data: [380, 385, 392, 398, 405, 412, 418]
  },
  {
    name: '低风险用户',
    data: [1520, 1535, 1548, 1562, 1578, 1585, 1592]
  }
])

// 高风险用户列表数据
const riskUsers = ref([
  {
    userId: 'U001234',
    userName: '张三',
    churnProbability: 0.89,
    riskLevel: 'High',
    lastActiveDate: '2024-01-10',
    totalOrders: 15,
    totalSpent: 12580,
    avgOrderValue: 839
  },
  {
    userId: 'U001235',
    userName: '李四',
    churnProbability: 0.76,
    riskLevel: 'High',
    lastActiveDate: '2024-01-08',
    totalOrders: 8,
    totalSpent: 6420,
    avgOrderValue: 803
  },
  {
    userId: 'U001236',
    userName: '王五',
    churnProbability: 0.65,
    riskLevel: 'Medium',
    lastActiveDate: '2024-01-12',
    totalOrders: 22,
    totalSpent: 18900,
    avgOrderValue: 859
  },
  {
    userId: 'U001237',
    userName: '赵六',
    churnProbability: 0.58,
    riskLevel: 'Medium',
    lastActiveDate: '2024-01-14',
    totalOrders: 12,
    totalSpent: 9650,
    avgOrderValue: 804
  },
  {
    userId: 'U001238',
    userName: '钱七',
    churnProbability: 0.32,
    riskLevel: 'Low',
    lastActiveDate: '2024-01-15',
    totalOrders: 35,
    totalSpent: 28900,
    avgOrderValue: 826
  }
])

// 图表配置（ECharts组件会自动处理）

// 计算属性
const filteredRiskUsers = computed(() => {
  let filtered = riskUsers.value

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(user =>
      user.userId.toLowerCase().includes(keyword) ||
      user.userName.toLowerCase().includes(keyword)
    )
  }

  // 风险等级过滤
  if (riskLevelFilter.value) {
    filtered = filtered.filter(user => user.riskLevel === riskLevelFilter.value)
  }

  return filtered
})

// 方法
const refreshData = async (showMessage = false) => {
  loading.value = true
  try {
    // 并行加载所有数据
    await Promise.all([
      loadOverviewData(),
      loadRiskDistribution(),
      loadTrendData(),
      loadRiskUsers()
    ])

    if (showMessage) {
      ElMessage.success('数据刷新成功')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 加载概览数据
const loadOverviewData = async () => {
  try {
    const response = await getChurnOverview()
    if (response.success && response.data) {
      // 安全地更新概览数据
      const overview = response.data.overview || {}
      overviewData.highRiskCount = overview.highRiskCount || 0
      overviewData.highRiskChange = overview.highRiskChange || 0
      overviewData.mediumRiskCount = overview.mediumRiskCount || 0
      overviewData.mediumRiskChange = overview.mediumRiskChange || 0
      overviewData.lowRiskCount = overview.lowRiskCount || 0
      overviewData.lowRiskChange = overview.lowRiskChange || 0
      overviewData.modelAccuracy = overview.modelAccuracy || 0
      overviewData.accuracyChange = overview.accuracyChange || 0

      // 安全地更新模型性能数据
      const performance = response.data.modelPerformance || {}
      Object.assign(modelPerformance, {
        accuracy: performance.accuracy || modelPerformance.accuracy,
        precision: performance.precision || modelPerformance.precision,
        recall: performance.recall || modelPerformance.recall,
        f1Score: performance.f1Score || modelPerformance.f1Score,
        version: performance.version || modelPerformance.version,
        trainTime: performance.trainTime || modelPerformance.trainTime,
        sampleCount: performance.sampleCount || modelPerformance.sampleCount
      })
    }
  } catch (error) {
    console.error('加载概览数据失败:', error)
    // 发生错误时保持默认数据
  }
}

// 加载风险分布数据
const loadRiskDistribution = async () => {
  try {
    const response = await getChurnRiskDistribution({ timeRange: riskTimeRange.value })
    if (response.success && response.data && Array.isArray(response.data)) {
      // 确保数据格式正确
      riskDistributionData.value = response.data.map(item => ({
        name: item.name || '未知',
        value: item.value || 0,
        color: item.itemStyle?.color || '#5f27cd'
      }))
      console.log('风险分布数据加载成功:', riskDistributionData.value)
    } else {
      // 如果API返回的数据格式不正确，使用默认数据
      console.warn('风险分布数据格式不正确，使用默认数据')
    }
  } catch (error) {
    console.error('加载风险分布数据失败:', error)
    // 发生错误时保持默认数据
  }
}

// 加载趋势数据
const loadTrendData = async () => {
  try {
    const response = await getChurnTrendData({ trendType: trendType.value })
    if (response.success && response.data && Array.isArray(response.data)) {
      // 提取日期标签
      const labels = response.data.map(item => item.date || '')
      trendLabels.value = labels

      // 构建图表数据
      const highRiskData = response.data.map(item => item.highRisk || 0)
      const mediumRiskData = response.data.map(item => item.mediumRisk || 0)
      const lowRiskData = response.data.map(item => item.lowRisk || 0)

      trendChartData.value = [
        {
          name: '高风险用户',
          data: highRiskData,
          color: '#F56C6C'
        },
        {
          name: '中风险用户',
          data: mediumRiskData,
          color: '#E6A23C'
        },
        {
          name: '低风险用户',
          data: lowRiskData,
          color: '#67C23A'
        }
      ]

      console.log('趋势数据加载成功:', {
        labels: trendLabels.value,
        data: trendChartData.value
      })
    } else {
      console.warn('趋势数据格式不正确，使用默认数据')
    }
  } catch (error) {
    console.error('加载趋势数据失败:', error)
    // 发生错误时保持默认数据
  }
}

// 加载风险用户列表
const loadRiskUsers = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      searchKeyword: searchKeyword.value,
      riskLevelFilter: riskLevelFilter.value
    }

    const response = await getChurnRiskUsers(params)
    if (response.success && response.data) {
      riskUsers.value = response.data.users || []
      const pagination = response.data.pagination || {}
      totalUsers.value = pagination.total_count || 0
    } else {
      // 如果API调用失败，清空列表
      riskUsers.value = []
      totalUsers.value = 0
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    // 发生错误时清空列表
    riskUsers.value = []
    totalUsers.value = 0
  }
}

const runPrediction = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要执行流失预测吗？这将为所有活跃用户生成最新的流失风险评估。',
      '确认执行预测',
      { type: 'warning' }
    )

    predicting.value = true

    const response = await runChurnPrediction()
    if (response.success) {
      ElMessage.success(response.message)
      // 刷新数据
      await refreshData()
    } else {
      ElMessage.error(response.message || '预测执行失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('执行预测失败:', error)
      ElMessage.error('预测执行失败')
    }
  } finally {
    predicting.value = false
  }
}

const exportResults = () => {
  // 导出预测结果
  const data = filteredRiskUsers.value
  const csvContent = [
    ['用户ID', '用户姓名', '流失概率', '风险等级', '最后活跃', '历史订单', '消费金额', '平均订单'],
    ...data.map(user => [
      user.userId,
      user.userName,
      user.churnProbability,
      user.riskLevel,
      user.lastActiveDate,
      user.totalOrders,
      user.totalSpent,
      user.avgOrderValue
    ])
  ].map(row => row.join(',')).join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `churn_prediction_${new Date().toISOString().split('T')[0]}.csv`
  link.click()

  ElMessage.success('预测结果已导出')
}

const getRiskColor = (riskLevel) => {
  const colorMap = {
    'high': '#F56C6C',
    'High': '#F56C6C',
    'medium': '#E6A23C',
    'Medium': '#E6A23C',
    'low': '#67C23A',
    'Low': '#67C23A'
  }
  return colorMap[riskLevel] || '#909399'
}

const getRiskTagType = (riskLevel) => {
  const typeMap = {
    'high': 'danger',
    'High': 'danger',
    'medium': 'warning',
    'Medium': 'warning',
    'low': 'success',
    'Low': 'success'
  }
  return typeMap[riskLevel] || 'info'
}

const getRiskLevelText = (riskLevel) => {
  const textMap = {
    'high': '高风险',
    'High': '高风险',
    'medium': '中风险',
    'Medium': '中风险',
    'low': '低风险',
    'Low': '低风险'
  }
  return textMap[riskLevel] || '未知'
}

const viewUserDetail = (user) => {
  selectedUser.value = user
  selectedUserPrediction.value = {
    // 模拟预测详细数据
    factors: [
      { name: '最后登录间隔', value: 15, impact: 'high' },
      { name: '购买频率下降', value: 60, impact: 'high' },
      { name: '客服咨询增加', value: 3, impact: 'medium' }
    ],
    recommendations: [
      '发送个性化优惠券',
      '推送相关产品推荐',
      '安排客服主动联系'
    ]
  }
  userDetailVisible.value = true
}

const createRetentionStrategy = (user) => {
  selectedUser.value = user
  strategyVisible.value = true
}

const handleCloseUserDetail = () => {
  userDetailVisible.value = false
  selectedUser.value = null
  selectedUserPrediction.value = null
}

const handleCloseStrategy = () => {
  strategyVisible.value = false
  selectedUser.value = null
}

const handleStrategyCreated = (strategy) => {
  ElMessage.success('挽回策略创建成功')
  strategyVisible.value = false
}

const handleSortChange = ({ column, prop, order }) => {
  // 实现排序逻辑
  console.log('排序变化:', { column, prop, order })
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 监听器
watch([riskTimeRange], () => {
  // 时间范围变化时重新加载风险分布数据
  loadRiskDistribution()
})

watch([trendType], () => {
  // 趋势类型变化时重新加载趋势数据
  loadTrendData()
})

watch([searchKeyword, riskLevelFilter, currentPage, pageSize], () => {
  // 搜索和筛选条件变化时重新加载用户列表
  loadRiskUsers()
})

// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.churn-prediction-page {
  padding: 0;
  background-color: transparent;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 概览统计 */
.overview-section {
  margin-bottom: 24px;
}

.metric-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
  height: 120px;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.metric-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.metric-card.high-risk .metric-icon {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
}

.metric-card.medium-risk .metric-icon {
  background: linear-gradient(135deg, #ffa726, #ff9800);
}

.metric-card.low-risk .metric-icon {
  background: linear-gradient(135deg, #66bb6a, #4caf50);
}

.metric-card.model-accuracy .metric-icon {
  background: linear-gradient(135deg, #42a5f5, #2196f3);
}

.metric-content {
  flex: 1;
}

.metric-content h3 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 700;
  color: #333;
}

.metric-content p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.metric-change {
  font-size: 12px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 12px;
}

.metric-change.success {
  background: #f0f9ff;
  color: #10b981;
}

.metric-change.warning {
  background: #fffbeb;
  color: #f59e0b;
}

.metric-change.danger {
  background: #fef2f2;
  color: #ef4444;
}

/* 卡片样式 */
.chart-card,
.performance-card,
.feature-importance-card,
.risk-users-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
}

/* 流失趋势分析卡片特殊样式 */
.chart-card:nth-of-type(2) {
  min-height: 500px;
}

/* 右侧卡片高度调整 */
.performance-card {
  min-height: 280px;
}

.feature-importance-card {
  min-height: 400px;
}

.chart-card :deep(.el-card__header),
.performance-card :deep(.el-card__header),
.feature-importance-card :deep(.el-card__header),
.risk-users-card :deep(.el-card__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 图表容器 */
.chart-container {
  padding: 20px;
  height: 400px;
}

/* 模型性能 */
.performance-metrics {
  padding: 20px 0;
}

.metric-item {
  margin-bottom: 20px;
}

.metric-item:last-child {
  margin-bottom: 0;
}

.metric-label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.metric-value {
  display: flex;
  align-items: center;
  gap: 12px;
}

.metric-value .el-progress {
  flex: 1;
}

.percentage {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  min-width: 45px;
}

.model-info {
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

.model-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

/* 特征重要性 */
.feature-list {
  padding: 20px 0;
}

.feature-item {
  margin-bottom: 16px;
}

.feature-item:last-child {
  margin-bottom: 0;
}

.feature-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.feature-name {
  font-size: 14px;
  color: #333;
}

.feature-value {
  font-size: 14px;
  font-weight: 600;
  color: #666;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}
</style>
